package chapter19.ReaderAndWriter;
import org.junit.jupiter.api.Test;

import java.io.FileReader;
import java.io.IOException;

/**
 * @Auther: Tx
 * @Date: 2022/7/23 21:19
 */
//字符流,不会产生乱码
public class FileReader1 {
    public static void main(String[] args) {

    }
//    单个字符读取文件
    @Test
    void test01(){
        String filePath = "e:\\hello.txt";
        FileReader fileReader = null;
        int data = 0;
        try {
            fileReader= new FileReader(filePath);
            while ((data = fileReader.read())!=-1){
                System.out.print((char)data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
//            关闭流
            try {
                fileReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

//一次读取多个字符
    @Test
    void test02(){
        String filePath = "e:\\hello.txt";
        FileReader fileReader = null;
        int readLen = 8;
        char[] data = new char[8];
        try {
            fileReader= new FileReader(filePath);
            while ((readLen= fileReader.read(data))!=-1){
                System.out.print(new String(data,0,readLen));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
//            关闭流
            try {
                fileReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
